﻿using UnityEngine;
using System.Collections;

public class paddleAutoControl : MonoBehaviour {
	
	public float speed = 10.0f; 
	private Transform ball; 
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (GameObject.FindWithTag("ball")) 
		{ 
			ball = GameObject.FindWithTag("ball").transform; 
			if (ball.position.y > 0) 
			{
			 	transform.position = new Vector3(Mathf.Lerp( transform.position.x, ball.position.x, speed * Time.deltaTime), transform.position.y, transform.position.z); 
			}
			transform.position = new Vector3(Mathf.Clamp( transform.position.x, -14, 14),transform.position.y, transform.position.z); 
		} 
	}
	
	void OnCollisionEnter(Collision collision) 
	{ 
		var velo = collision.rigidbody.velocity.magnitude; 
		collision.rigidbody.velocity = new Vector3((collision.transform.position.x - transform.position.x)*8, collision.rigidbody.velocity.y, collision.rigidbody.velocity.z); 
		if (collision.rigidbody.velocity.magnitude < velo) 
		{
			collision.rigidbody.velocity *= velo/collision.rigidbody.velocity.magnitude; 
		}
	} 
}
